package cn.luckdou.system.service.impl.we_chat;

import cn.luckdou.system.model.we_chat.WeChat;
import cn.luckdou.system.mapper.we_chat.WeChatMapper;
import cn.luckdou.system.service.we_chat.IWeChatService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Dadou
 * @since 2017-08-08
 */
@Service
public class WeChatServiceImpl extends ServiceImpl<WeChatMapper, WeChat> implements IWeChatService {
    @Autowired
    private WeChatMapper weChatMapper;

    @Override
    @Transactional
    public Integer insert(String userInfo) {
        JSONObject json = JSONObject.fromObject(userInfo);
        WeChat weChat=new WeChat(json);
        List<WeChat> list = weChatMapper.selectList(new EntityWrapper<WeChat>().eq("open_id", weChat.getOpenId()).eq("status", 1));
        if (list!=null && list.size()>0){
            weChat.setId(list.get(0).getId());
            Integer integer = weChatMapper.updateById(weChat);
            return integer;
        }else{
            Integer insert = weChatMapper.insert(weChat);
            return insert;
        }
    }

    @Override
    @Transactional
    public Integer updateToSubscribe(String openid) {
        Integer integer=0;
        List<WeChat> list = weChatMapper.selectList(new EntityWrapper<WeChat>().eq("open_id", openid).eq("status", 1));
        if (list!=null && list.size()>0){
            for (WeChat weChat : list) {
                weChat.setSubscribe(0);
                weChat.setRemoveDate(new Date());
                integer += weChatMapper.updateById(weChat);
            }
        }
        return integer;
    }

}
